package track_formats

import (
	"time"

	"github.com/pion/rtp"
	"gogs.smarteye.com/servere/gobvrtp/encoder"
	"gogs.smarteye.com/servere/gobvrtp/track"
)

type TSPTrack struct {
	ApplicationTrack

	encoder *encoder.RTPEncoder
	decoder *encoder.RTPDecoder
}

func NewTSPTrack() *TSPTrack {
	c := &TSPTrack{}

	param := c.CtlParma()
	param.SetPayloadType(113)
	param.SetCodec(track.CodecIdTSP)
	param.SetClockRate(90000)
	param.SetOnReadRTPFunc(c.onRTP)

	return c
}

func (c *TSPTrack) WritePacket(t time.Time, data []byte) error {
	param := c.CtlParma()

	if c.encoder == nil {
		// 初始化编码器
		e := &encoder.RTPEncoder{
			SampleRate:            c.ClockRate(),
			PayloadType:           c.PayloadType(),
			SSRC:                  ToPtr(c.SSRC()),
			InitialSequenceNumber: ToPtr(param.InitialSequenceNumber),
			PayloadMaxSize:        param.PayloadMaxSize,
		}

		_ = e.Init()
		c.encoder = e
	}

	packets, err := c.encoder.Encode(data, 0)
	if err != nil {
		return err
	}

	timestamp, _ := c.CtlParma().RtpTimeEncode(t)

	for _, pkt := range packets {
		packet := pkt
		packet.Timestamp = timestamp
		if err = c.WriteRTP(packet); err != nil {
			return err
		}
	}

	return nil
}

func (c *TSPTrack) onRTP(_ track.Track, pkt *rtp.Packet) {
	packets, _ := c.Detector(pkt)

	if c.decoder == nil {
		// 初始化解码器
		decoder := &encoder.RTPDecoder{
			SampleRate: c.ClockRate(),
		}
		_ = decoder.Init()
		c.decoder = decoder
	}

	for _, packet := range packets {
		if data, err := c.decoder.Decode(packet); err == nil {
			for _, nalu := range data {
				c.onFrame(packet, nalu)
			}
		}
	}
}

func init() {
	RegisterTrack(track.CodecIdTSP, func() track.Track {
		return NewTSPTrack()
	})
}
